package thread.wang_bao_ling.c20;

import org.junit.Test;
import thread.wang_bao_ling.c15.SynchronizatizedQueue;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Auther: luobiao
 * @Date: 2020/7/19 09:17
 * @Description:
 */
public class LinkedBlockingQueueTest {
    @Test
    public void test1() throws InterruptedException {
        LinkedBlockingQueue queue=new LinkedBlockingQueue(2);
        CountDownLatch countDownLatch = new CountDownLatch(7);
        enq(queue,"one","t1",0,countDownLatch);
        enq(queue,"two","t2",100,countDownLatch);
        enq(queue,"three","t3",200,countDownLatch);
        enq(queue,"four","t4",300,countDownLatch);
        enq(queue,"five","t5",400,countDownLatch);
        deq(queue,"t6",1000,countDownLatch);
        deq(queue,"t7",1500,countDownLatch);
        countDownLatch.await();
        System.out.println(queue.size());

    }


    public static void enq(LinkedBlockingQueue queue, Object o, String threadName, int delay,CountDownLatch countDownLatch) {
        new Thread(() -> {
            try {
                if (delay > 0) {
                    Thread.currentThread().sleep(delay);
                }
                queue.put(o);
                System.out.println("put--->"+o);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                countDownLatch.countDown();
            }
        }, threadName).start();
    }

    public static void deq(LinkedBlockingQueue queue, String threadName,int delay,CountDownLatch countDownLatch) {
        new Thread(() -> {
            try {
                if (delay > 0) {
                    Thread.currentThread().sleep(delay);
                }
                Object o= queue.take();
                System.out.println("take--->"+o);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                countDownLatch.countDown();
            }
        }, threadName).start();
    }
}
